package com.kunpan.admin.async;

import com.kunpan.admin.common.Enum.FileStatusEnum;
import com.kunpan.admin.entity.PanFile;
import com.kunpan.admin.mapper.PanFileMapper;
import com.kunpan.admin.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@EnableScheduling   // 开启定时任务
@Component
public class FileExpiredClearTask {

    private static final Logger Logger = LoggerFactory.getLogger(FileExpiredClearTask.class);
    @Autowired
    private PanFileMapper panFileMapper;

    @Autowired
    private UserMapper userMapper;

    @Async("scheduledExecutorService")
    @Scheduled(cron = "0 0 0 * * ?")//每天凌晨12点执行
//    @Scheduled(cron = "*/20 * * * * ?")
    @Transactional
    public void clearExpiredFile() {
        Logger.info("开始执行:清理在回收站超过7天的文件");
        //根据userId进行分组求和查询出在回收站超过七天的总文件大小
        List<PanFile> list = panFileMapper.selectRecycleFileList();
        if (list.isEmpty()) {
            return;
        }
        //先将文件状态设为彻底删除
        panFileMapper.clearRecycleFile(FileStatusEnum.CLEAN.getValue());
        //在更新用户内存
        userMapper.updateUserSpaceByIds(list);
        Logger.info("执行成功");
    }
}
